/**
 * 
 */
package com.jie.eclipse.pan.editors.utils;

import java.util.HashMap;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.jie.eclipse.pan.Activator;

/**
 * @author yanjie
 * 
 */
public class PanImageHelper {

	private final String PLUGINID = "org.eclipse.wst.pan.ui";
	private static PanImageHelper instance = null;

	private HashMap fImageDescRegistry = null;

	public static synchronized PanImageHelper getInstance() {
		if (instance == null)
			instance = new PanImageHelper();
		return instance;
	}

	public Image getImage(String resource) {
		Image image = getImageRegistry().get(resource);
		if (image == null) {
			image = createImage(resource);
		}
		return image;
	}

	public ImageDescriptor getImageDescriptor(String resource) {
		ImageDescriptor imageDescriptor = null;
		Object o = getImageDescriptorRegistry().get(resource);
		if (o == null) {
			imageDescriptor = createImageDescriptor(resource);
		} else {
			imageDescriptor = (ImageDescriptor) o;
		}
		return imageDescriptor;
	}
	
	public ImageDescriptor getPanImageDescriptor(){
		return this.getImageDescriptor("/icons/pan.jpg");
	}

	private HashMap getImageDescriptorRegistry() {
		if (this.fImageDescRegistry == null)
			this.fImageDescRegistry = new HashMap();
		return this.fImageDescRegistry;
	}

	private ImageRegistry getImageRegistry() {
		return Activator.getDefault().getImageRegistry();
	}

	private Image createImage(String resource) {
		ImageDescriptor desc = getImageDescriptor(resource);
		Image image = null;

		if (desc != null) {
			image = desc.createImage();

			if (!(desc.equals(ImageDescriptor.getMissingImageDescriptor())))
				getImageRegistry().put(resource, image);
		}
		return image;
	}

	private ImageDescriptor createImageDescriptor(String imageFilePath) {
		ImageDescriptor imageDescriptor = AbstractUIPlugin
				.imageDescriptorFromPlugin("com.jie.eclipse.pan",
						imageFilePath);
		if (imageDescriptor != null) {
			getImageDescriptorRegistry().put(imageFilePath, imageDescriptor);
		} else {
			imageDescriptor = ImageDescriptor.getMissingImageDescriptor();
		}

		return imageDescriptor;
	}

}
